/* 
 * Since 2008 - 2012
 */
package com.hh.bss.sysadmin.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.filters.MappingPropertyFilter;
import net.sf.json.util.PropertyFilter;

import org.springframework.stereotype.Controller;

import com.hh.bss.base.BaseSpringController;
import com.hh.bss.common.cache.SystemDicCache;
import com.hh.bss.common.cache.SystemDicMapCache;
import com.hh.bss.common.page.Page;
import com.hh.bss.common.page.PageRequest;
import com.hh.bss.sysadmin.entity.SystemDicMap;
import com.hh.bss.sysadmin.service.SystemDicMapService;
import com.hh.bss.sysadmin.vo.query.SystemDicMapQuery;
import com.hh.bss.sysadmin.vo.query.SystemDicQuery;
import com.hh.bss.util.StringHelper;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

@Controller
public class SystemDicMapController extends BaseSpringController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;

	private SystemDicMapService systemDicMapService;

	private SystemDicMap systemDicMap;

	java.lang.Integer id = null;
	private String[] items;

	/** 通过spring自动注入 */
	public void setSystemDicMapServiceImpl(SystemDicMapService service) {
		this.systemDicMapService = service;
	}

	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/**
	 * ExtGrid使用 列表
	 * 
	 * @throws IOException
	 */
	public void list(HttpServletRequest request, HttpServletResponse response, SystemDicMapQuery systemDicMapQuery) throws IOException {
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = systemDicMapService.findPage(systemDicMapQuery);

		List<SystemDicMap> SystemDicMaplist = (List) page.getResult();
		ListRange<SystemDicMap> resultList = new ListRange<SystemDicMap>();
		resultList.setRows(SystemDicMaplist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response, resultList);
	}

	/**
	 * extGrid保存
	 * 
	 * @throws IOException
	 */
	public void save(HttpServletRequest request, HttpServletResponse response, SystemDicMap systemDic) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			// 设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemDicMap.class, "creator")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(systemDicMap, "creator", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemDicMap.class, "createDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(systemDic, "createDt", new Date());
				} catch (Exception ex) {
				}
			}

			systemDicMapService.save(systemDic);
			result.put("success", true);
			result.put("msg", "添加成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid修改
	 * 
	 * @throws IOException
	 */
	public void update(HttpServletRequest request, HttpServletResponse response, SystemDicMap systemDic) throws IOException {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			SystemDicMap oldsystemDic = (SystemDicMap) systemDicMapService.getById(systemDic.getId());

			bind(request, oldsystemDic);
			// 设置修改用户和修改时间
			com.hh.bss.auth.client.OnlineManager onlineManager = super.getOnlineManager(request, response);
			if (onlineManager != null) {
				com.hh.bss.auth.client.OnlineUser onlineUser = onlineManager.getOnlineUser();
				if (onlineUser != null && com.hh.bss.util.BeanUtils.isExistsProperty(SystemDicMap.class, "modifier")) {
					try {
						com.hh.bss.util.BeanUtils.setProperty(oldsystemDic, "modifier", onlineUser.getUsername());
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				}
			}

			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemDicMap.class, "modifiedDt")) {
				try {
					com.hh.bss.util.BeanUtils.setProperty(oldsystemDic, "modifiedDt", new Date());
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			systemDicMapService.update(oldsystemDic);
			result.put("success", true);
			result.put("msg", "修改成功!");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	/**
	 * extGrid删除
	 * 
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			for (int i = 0; i < idarray.length; i++) {
				java.lang.Integer id = new java.lang.Integer((String) idarray[i]);
				systemDicMapService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		} catch (Exception e) {
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response, result);
	}

	public void listconstdic(HttpServletRequest request, HttpServletResponse response, SystemDicQuery systemDicQuery) throws IOException {

	}

	@SuppressWarnings("unchecked")
	public void listdic(HttpServletRequest request, HttpServletResponse response, SystemDicMapQuery systemDicMapQuery) throws IOException {
		try {

			Object categorys = null;
			boolean isVar = false;
			if (!StringHelper.isEmpty(request.getParameter("isvar"))) {
				isVar = true;
			}

			if (StringHelper.isEmpty(systemDicMapQuery.getCategory())) {

				categorys = SystemDicMapCache.getSystemDicCategoryListMap();
			} else {
				categorys = SystemDicMapCache.getCategoryList(systemDicMapQuery.getCategory());

			}

			JsonConfig jsonConfig = new JsonConfig();
			@SuppressWarnings("rawtypes")
			Map mf = new HashMap();
			mf.put(SystemDicMap.class, new PropertyFilter() {
				public boolean apply(Object source, String name, Object value) {
					// name--map里key的字符，或是bean里的属性
					// map里的value,或是bean里的属性的值
					// 如果上层的数据给拦截了，那底层的数据将不能被转换
					// source 可能是hash或bean等
					Set set = new HashSet();
					set.add("id");
					//set.add("category");
					set.add("keyId");
					set.add("keyMapIds");
					if (SystemDicMap.class.equals(source.getClass()) && !set.contains(name)) {
						return true;
					}
					return false;
				}
			});
			jsonConfig.setJsonPropertyFilter(new MappingPropertyFilter(mf) {
				protected boolean keyMatches(Object key, Object source, String name, Object value) {
					return true;
				}
			});

			// System.out.println(JSONObject.fromObject(m,jsonConfig).toString());
			StringBuffer sb = new StringBuffer();

			String jsonStr = "";

			if (isVar)
				jsonStr = JSONObject.fromObject(categorys, jsonConfig).toString();
			else
				jsonStr = JSONArray.fromObject(categorys, jsonConfig).toString();

			if (isVar)
				sb.append(" var allDicMap =").append(jsonStr).append(";");
			else
				sb.append(jsonStr);
			JsonHelper.outJsonString(response, sb.toString());
			// systemDicCache.setSystemDicDaoImpl(systemDicService.g);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
